package com.lcp.se.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lcp.se.entity.data.Chat;
import com.lcp.se.entity.result.PageResultForMini;
import com.lcp.se.entity.result.Result;
import com.lcp.se.mapper.ChatMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author lcp
 * @date 2020/8/5 21:55
 */
@Service
public class ChatService {
    private final Logger log = LoggerFactory.getLogger(AmqpMessageService.class);

    @Resource
    private AmqpMessageService amqpMessageService;

    @Resource
    private ChatMapper chatMapper;

    /**
     * 保存并发送聊天消息
     */
    public Result<String> send(Chat chat) {
        chat.setIfRead(0);
        if (chatMapper.insert(chat) != 1) {
            return Result.failure();
        }
        try {
            amqpMessageService.sendMessage(chat);
        } catch (Exception e) {
            log.error("发送出错：" + e.getMessage());
        }
        return Result.success("发送成功");
    }

    /**
     * 查询指定预约的聊天记录
     */
    public Result<PageResultForMini<Chat>> list(String appointmentId, Integer pageSize, Integer currentPage) {
        pageSize = pageSize == null ? 10 : pageSize;
        currentPage = currentPage == null ? 1 : currentPage;
        int index = pageSize * (currentPage - 1);
        QueryWrapper<Chat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("appointment_id", appointmentId);
        Integer count = chatMapper.selectCount(queryWrapper);
        queryWrapper.orderByDesc("create_time").last("limit " + index + "," + pageSize);
        List<Chat> chats = chatMapper.selectList(queryWrapper);
        PageResultForMini<Chat> pageResult = new PageResultForMini<>(chats, pageSize, currentPage, count);
        return Result.success("查询成功", pageResult);
    }

}
